package cn.fx.baseweb.controller;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.Map;

/**
 * 设置自定义错误（400、500）页面
 */
public class CustomErrorController implements ErrorController {

    private final static Map<Integer, String> codePageMap = new HashMap<>() {
        {
            put(HttpStatus.NOT_FOUND.value(), "/error/404.html");
            put(HttpStatus.INTERNAL_SERVER_ERROR.value(), "/error/500.html");
        }
    };

    @RequestMapping(value = "/error", produces = MediaType.TEXT_HTML_VALUE)
    public String errorView(HttpServletRequest request){
        //从request对象中获取状态码
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        request.setAttribute("statusCode","错误状态码："+status);

        if (ObjectUtils.isEmpty(status)){
            return this.getDefaultView();
        }

        //若状态码包含在map映射中，就返回到指定的错误页面
        Integer statusCode = Integer.valueOf(status.toString());
        if(codePageMap.containsKey(statusCode)){
            return codePageMap.get(statusCode);
        }
        return this.getDefaultView();
    }

    private String getDefaultView(){
        return codePageMap.get(HttpStatus.INTERNAL_SERVER_ERROR.value());
    }

}
